<?php

namespace app\api\controller;

use think\Controller;
use think\Request;
use think\Validate;
use app\util\Utils;
use think\Db;
use app\admin\model\Code;

class HetController extends Controller {
    /*
     * 新建数据表  da_auth_account
     * 新建数据表  da_het_custom
     * 新建数据表  da_het_data
     */

    /*
     * code列表
     */

    public function code() {
        /*
         * 0  成功
         * 1  参数错误
         * 2  验证失败
         * 3  请求黑名单
         * 4  token无效
         * 1001  令牌授权错误
         * 8001  请求参数错误
         * 9999  其它错误
         * 
         * 8002  认证账号错误
         * 8003  签名失败
         * 8004  请输入真实手机号
         * 8005  验证码发送频繁
         * 8006  验证码发送失败
         * 8007  快捷注册失败
         * 8008
         * 
         */
    }

    //ip白名单
    public static $ipWhiteList = ['127.0.0.1', '221.221.139.94'];

    //和而泰认证账号
    const CPId = 1000099;
    const CPSecret = 'F316BD4449B890E270DCE293AD75A655'; //md5('和而泰to克克美')32位大

    /*
     * 验证请求方的合法性
     */

    public function _initialize() {
        $token = input('?param.token') ? input('param.token') : 0;
        $ip = $_SERVER['REMOTE_ADDR'];
        $request = Request::instance();
        $url = $request->url(true);
        $module = $request->module(); //模块名
        $controller = $request->controller(); //控制器名
        $action = $request->action(); //方法名
//        if(in_array($ip, self::$ipWhiteList)){
//            
//        }  else {
//            echo Utils::ajaxReturn(3, '请求黑名单', null);die;
//        }
        if ($action != 'auth') {//auth方法不需要验证
            if ($token) {
                $accountRow = Db::name('auth_account')
                        ->where('token', '=', $token)
                        ->where('update_time', '>', time() - 604800)//7天有效期
                        ->find();
                if (empty($accountRow)) {
                    echo Utils::ajaxReturn(4, 'token无效', null);
                    die;
                }
            } else {
                echo Utils::ajaxReturn(4, 'token无效', null);
                die;
            }
        }
    }

    /*
     * 返回数据
     */

    public static function ajaxReturn($code, $msg, $data) {
        $return = [
            'code' => $code,
            'msg' => $msg,
            'data' => $data
        ];

        return $return;
    }

    /*
     * 身份验证
     * 作者 xfwed
     * 日期 2019-08-23
     *
     * @param number cpid 合作方账号ID
     * @param string sign 合作方认证签名
     */

    public function auth() {
        $rule = [
            'cpid' => 'require|length:7',
            'sign' => 'require',
        ];
        $msg = [
            'cpid.require' => '合作方账号ID必须',
            'cpid.length' => '合作方账号ID长度为7',
            'sign.require' => '合作方认证签名必须',
        ];

        $all = input('param.');

        $validate = new Validate($rule, $msg);
        if (!$validate->check($all)) {
            $error = $validate->getError();

            return $this->ajaxReturn(1, $error, null);
        }

        $cpid = $all['cpid'];
        $sign = $all['sign'];
        $accountRow = Db::name('auth_account')->where('CPId', '=', $cpid)->find();
        if (empty($accountRow)) {
            return $this->ajaxReturn(8002, '认证账号错误', null);
        }
        $cpSecret = $accountRow['CPSecret'];
        $adminSign = md5(md5($cpid . $cpSecret) . $cpid . "kkmei");
        if ($sign != $adminSign) {
            return $this->ajaxReturn(8003, '签名失败', null);
        }
        $token = md5(md5($cpid . time()) . $adminSign);

        $result = Db::name('auth_account')
                ->where('CPId', '=', $cpid)
                ->update(['token' => $token, 'update_time' => time()]);
        $resultdata['cpid'] = $cpid;
        $resultdata['token'] = $token;
        if ($result) {
            return $this->ajaxReturn(0, '令牌授权成功', $resultdata);
        } else {
            return $this->ajaxReturn(1001, '令牌授权错误', $resultdata);
        }
    }

    /*
     * 注册发送验证码
     * 作者 xfwed
     * 日期 2019-08-27
     *
     * @param int custom_phone 客户账号
     * @param int type 验证码类型 21注册验证码 22忘记密码验证码
     */

    public function sendCode($token = '666', $phone = '15733262675') {
        $rule = [
            'token' => 'require',
            'phone' => 'require',
        ];
        $msg = [
            'token.require' => 'token必须',
            'phone.require' => '手机号必须',
        ];

        $all = input('param.');

        $validate = new Validate($rule, $msg);
        if (!$validate->check($all)) {
            $error = $validate->getError();

            return $this->ajaxReturn(1, $error, null);
        }

        $custom_phone = $all['phone'];
        $type = 21;

        if (!Utils::checkTelephone($custom_phone)) {
            return $this->ajaxReturn(8004, '请输入真实手机号', null);
        }

        $canSend = Code::canSendCode($custom_phone, $type);
        if (!$canSend) {
            return $this->ajaxReturn(8005, '验证码发送频繁', null);
        }

        //$code = mt_rand(1000, 9999);
        $code = Code::makerCode($custom_phone, $type);
        $content = '';
        if ($type == Code::TYPE_21) {
            $content = $code . '（您本次操作克克美的验证码），验证码有效期15分钟。请勿转发，否则会导致账号被盗。';
        }

        $sendResult = Utils::sendSms($custom_phone, $content);
        if ($sendResult['code'] == 'success') {
            //写入验证码
            $codeData = [
                'type' => $type,
                'telephone' => $custom_phone,
                'code' => $code,
                'status' => Code::STATUS_1,
                'add_time' => date('Y-m-d H:i:s'),
            ];

            Code::insert($codeData);

            $data['verifyCode'] = $code;

            return $this->ajaxReturn(0, '验证码发送成功', $data);
        } else {
            return $this->ajaxReturn(8006, $sendResult['msg'], null);
        }
    }

    /*
     * 手机号快捷登录/注册
     * 日期 2019-08-27
     *
     * @param string custom_phone 客户账号
     * @param string code 验证码
     * @param int store_id 店铺编号 非必须
     * 
     * 1.先登录，如果没有注册账号去注册
     * 2.如果code=9999则为微信手机号快速登录，不需要验证
     * 3.如果store_id = 0 则只登录不注册 否则先登录，没有账号去注册
     */

    public function fastLoginOrRegister() {
        $phone = input('param.phone');
        $wechat = input('param.wechat');
        $mmid = input('param.mmid');
        if (empty($phone) || empty($wechat)) {
            return $this->ajaxReturn(1, '参数错误', null);
        }


        $wechat = json_decode($wechat, true);
        $openid = $wechat['openid'];
        $unionid = $wechat['unionid'];
        $nickname = $wechat['nickname'];
        $headimgurl = $wechat['headimgurl'];
        $province = $wechat['province'];
        $weicity = $wechat['weicity'];
        $sex = $wechat['sex'];

        $custom_phone = $phone;

        $ctmRow = Db::name('custom')->where('custom_phone', '=', $custom_phone)->find();
        if ($ctmRow) {
            if ($ctmRow['status'] == 1) {
                Db::name('custom')->where('custom_phone', '=', $custom_phone)->update(['status' => 2]);
                $row = [
                    'userId' => $ctmRow['id'],
                ];
                return $this->ajaxReturn(0, '登录成功', $row);
            } else {
                $row = [
                    'userId' => $ctmRow['id'],
                ];
                return $this->ajaxReturn(0, '登录成功', $row);
            }
        } else {
            $data = [
                'source' => 3,
                'custom_phone' => $custom_phone,
                'add_time' => date('Y-m-d H:i:s'),
            ];
            $insertId = Db::name('custom')->insertGetId($data);
            $row = [
                'userId' => $insertId,
            ];
            return $this->ajaxReturn(0, '注册成功', $row);
        }
    }

    /*
     * 检测皮肤数据回传
     * 日期 2019-08-28
     *
     */

    public function magicMirror() {
        $phone = input('param.phone');
        $mmid = input('param.mmid');
        $skindata = input('param.skindata');
        $h5url = input('param.h5url');
        $score = input('param.totalScore');
        $type = input('param.type');//1魔镜测肤 3仪器测肤
        if (!isset($phone) || !isset($skindata) || !isset($h5url) || !isset($score)) {
            return $this->ajaxReturn(1, '参数错误', null);
        }
        if(empty($type)){
            $type = 1;
        }

        $a = [
            "photographId" => 1543119,
            "userPic" => "test",
            "totalScore" => 90,
            "skinAnalysisScore" => null,
            "blackHeadDeduction" => null,
            "wrinkleDeduction" => -4,
            "poreDeduction" => null,
            "acneDeduction" => null,
            "pigmentationDeduction" => -2,
            "pouchDeduction" => null,
            "skinColorDeduction" => null,
            "blackheadPoreDeduction" => null,
            "moistureDeduction" => -3,
            "sensitiveDeduction" => -1,
            "problemNum" => 2,
            "facecolorLevelName" => null,
            "acneLevelName" => null,
            "pigmentationLevelName" => null,
            "wrinkleLevelName" => null,
            "pouchLevelName" => null,
            "blackheadLevelName" => null,
            "poreLevelName" => null,
            "skinTypes" => [],
            "skinTypeWithPics" => null,
            "photographSkinFacecolor" => [],
            "mostSeriousAcne" => null,
            "pimple" => null,
            "erythema" => null,
            "papules" => null,
            "pustule" => null,
            "nodule" => null,
            "scar" => null,
            "acneOverall" => null,
            "mole" => null,
            "chloasma" => null,
            "freckles" => null,
            "hidingSpot" => [],
            "mostSeriouspigmentation" => [],
            "pigmentationOverall" => null,
            "foreheadWrinkle" => [],
            "tearTrough" => [],
            "nasolabialFolds" => [],
            "risoriusMuscle" => [],
            "mostSeriousPhotographSkinWrinkle" => [],
            "wrinkleOverall" => null,
            "photographSkinPouch" => [],
            "photographSkinBlackhead" => [],
            "photographSkinPore" => [],
            "blackheadPore" => null,
            "photographFigureFeature" => [],
            "leftPhotographFigureEyebrow" => [],
            "rightPhotographFigureEyebrow" => [],
            "photographFigureEyeshape" => [],
            "photographFigureFurrows" => [],
            "blackHeadPic" => "http://200.200.200.58:8981/group2/M00/0F/1A/yMjIOlpLWkuAEQoZAAADpHz-wCg016.png",
            "wrinklePic" => "http://200.200.200.58:8981/group2/M00/0F/19/yMjIOlpK8aWANVtyAAAF0y-WzFM700.png",
            "porePic" => null,
            "acnePic" => null,
            "pigmentationPic" => "",
            "pouchPic" => null,
            "skinColorPic" => "",
            "photographMedals" => [],
            "shareDesc" => null,
            "sex" => 1,
            "similitudeStarPercent" => 55,
            "similitudeStarFace" => "郭德纲",
            "similitudeStarPic" => "http://skintest.hetyj.com/950f021c9a4466babc2c1dc0a4aa9f12.jpg",
            "measureTime" => "2018-11-2112:01:42",
            "resultType" => null,
            "skinSensitive" => [],
            "skinType" => [],
            "moistureOverall" => [],
            "photographMoisture" => null,
            "oilOverall" => [],
            "hasTakePhoto2_4_5" => true
        ];
        $a = json_encode($a);

        //$skindata = json_decode($skindata,true);
        
        //根据手机号和店铺id 找用户id
        $customRow = Db::name('custom')
                ->where('custom_phone', '=', $phone)
                ->field('id')
                ->find();
        if(empty($customRow)){
            return $this->ajaxReturn(1, '没有找到该用户', null);
        }
        $ctm_id = $customRow['id'];
        $data['phone'] = $phone;
        $data['mmid'] = $mmid;
        $data['ctm_id'] = $ctm_id;
        $data['csdata'] = $skindata;
        $data['type'] = $type;
        $data['h5url'] = $h5url;
        $data['score'] = $score;
        $data['add_time'] = date('Y-m-d H:i:s');
        $result = Db::name('het_data')->insert($data);
        if ($result) {
            return $this->ajaxReturn(0, '回传成功', null);
        }
    }

    /*
     * 体脂秤检测数据回传
     * 日期 2019-08-28
     *
     */

    public function bmiData() {
        $phone = input('param.phone');
        $mmid = input('param.mmid');
        $bmi = input('param.bmi');
        if (!isset($phone) || !isset($mmid) || !isset($bmi)) {
            return $this->ajaxReturn(1, '参数错误', null);
        }

        $a = [
            "dataId" => 134,
            "type" => 11,
            "ratio" => 89, // *100
            "label" => "偏低",
            "rangeValue" => [ // *100
                0,
                4608,
                5184,
                6336,
                6912,
                15000
            ],
            "rangeName" => [
                "严重不⾜",
                "偏低",
                "标准",
                "偏⾼",
                "严重超标"
            ],
            "nounInterpretation" => " ",
            "flag" => 0,
            "originValue" => 5111, // *100
            "dataId" => 134,
            "type" => 12,
            "ratio" => 100,
            "label" => "偏低",
            "rangeValue" => [
                0,
                4500,
                6000,
                10000
            ],
            "rangeName" => [
                "偏低",
                "标准",
                "充⾜"
            ],
            "description" => "您的体内水分率有点偏低。水分率偏低会影响⼈体的新陈代谢速率，还可能会影响体脂肪率以及肌肉量的比例哦，更别提肌肤是时刻离不开水分的滋养的。快给自己来一次深层身体护理吧！",
            "nounInterpretation" => "水分率即身体中水分占体重的百分比。因为肌⾁中含⼤量⽔分(⼤概70%），所以⽔分率能够反应减重的⽅式是否正确。",
            "flag" => 0,
            "originValue" => 5120
        ];
        $a = json_encode($a);

        //$skindata = json_decode($skindata,true);
        
        //根据手机号和店铺id 找用户id
        $customRow = Db::name('custom')
                ->where('custom_phone', '=', $phone)
                ->field('id')
                ->find();
        $ctm_id = $customRow['id'];
        $data['phone'] = $phone;
        $data['mmid'] = $mmid;
        $data['ctm_id'] = $ctm_id;
        $data['csdata'] = $bmi;
        $data['type'] = 2;
        $data['add_time'] = time();
        $result = Db::name('het_data')->insert($data);
        if ($result) {
            return $this->ajaxReturn(0, '回传成功', null);
        }
    }

}

?>